﻿using AutoMapper;
using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.DTO;
using Max.PH6_2006A.LowCode.DTO.Employee;
using Max.PH6_2006A.LowCode.IRespository;
using Max.PH6_2006A.LowCode.IService;
using System.Data;

namespace Max.PH6_2006A.LowCode.Service
{
    public class EmployeeService : BaseService<Employee, Employee, Employee>, IEmployeeService
    {
        IEmployeeRespository _respository;
        public EmployeeService(IEmployeeRespository respository,IMapper map) : base(respository,map)
        {
            _respository = respository;
        }

        public async Task<Tuple<bool,string>> ImportAsync(Microsoft.AspNetCore.Http.IFormFileCollection file,bool isCreateUser = true)
        {
            try
            {
                //上传文件
                var upload = Max.PH6_2006A.LowCode.Common.FileHelper.FileUploadAsnyc(file);

                //读取文件内容
                var stream = System.IO.File.Open(upload.Result.Item3[0], FileMode.Open);
                var data = Max.PH6_2006A.LowCode.Common.NpoiHelper.ReadStreamToDataTable(stream);

                List<EmployeeImportDto> list = new();
                foreach (DataRow item in data.Rows)
                {
                    EmployeeImportDto employee = new();
                    employee.Name = Convert.ToString(item["Name"]);
                    employee.EmployeeNo = Convert.ToString(item["EmployeeNo"]);
                    employee.Age = Convert.ToInt32(item["Age"]);
                    employee.HighestEduction = Convert.ToString(item["HighestEduction"]);
                    employee.InDate = Convert.ToDateTime(item["InDate"]);
                    employee.Birthday = Convert.ToDateTime(item["Birthday"]);
                    employee.Gender = Convert.ToString(item["Gender"]);
                    //employee.OrganizationalId= Convert.ToString(item["EmployeeNo"]);
                    //employee.PostId= Convert.ToString(item["EmployeeNo"]);

                    if (isCreateUser)
                    {
                        employee.Password = MD5Hash.Hash.Content(employee.EmployeeNo + "0000" +
                            "");
                    }
                    list.Add(employee);
                }

                string sql = "insert into Employee(EmployeeNo,Name,Age) values(@EmployeeNo,@Name,@Age);";
                if (isCreateUser)
                    sql = "insert into Employee(EmployeeNo,Name,Age) values(@EmployeeNo,@Name,@Age);" +
                    "insert into SystemUser(LoginName,Password,NickName) values(@EmployeeNo,@Password,@Name)";


                var result = await _respository.ExecuteAsync(sql, list);

                return Tuple.Create(result > 0, "上传成功");
            }
            catch (Exception ex)
            {
                return Tuple.Create(false, ex.Message);
            }
        }
    }
}
